import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.concurrent.Callable;

@Controller
public class AsynController {


    /**
     * 1.控制器返回Callable
     * 2.Spring异步处理，将Callable提交到TaskExecutor 使用一个隔离的线程执行
     * 3.DispatcherServlet和所有的Filter退出容器的线程，但是Response保持打开状态
     * 4.Callable返回结果，SpringMVC将重新派发给ioc容器，恢复之前的请求的处理
     * 5.根据Callable返回的结果，SpringMvc将继续进行视图渲染流程等(从接受到请求----视图渲染等)
     *
     * preHandle......./asyn01
     * thread 1 startThread[http-bio-8080-exec-10,5,main]
     * thread 1 endThread[http-bio-8080-exec-10,5,main]
     *
     * ======等待Callable执行
     * thread 2 startThread[MvcAsync1,5,main]
     * thread 2 endThread[MvcAsync1,5,main]
     *
     * =====Callable执行完
     * preHandle......./asyn01
     * postHandle.......(Callable的之前的返回值就是目标方法的返回值)
     * afterCompletion.......
     *
     * 异步的拦截器
     *      1.原生的API的AsyncListener
     *      2.SpringMvc；实现AsyncHandleInterceptor
     * */
    @ResponseBody
    @RequestMapping("/asyn01")
    public Callable<String> asyn01(){
        System.out.println("thread 1 start"+Thread.currentThread());

        Callable callable = new Callable<String>() {
            public String call() throws Exception {
                System.out.println("thread 2 start"+Thread.currentThread());
                Thread.sleep(2000);
                System.out.println("thread 2 end"+Thread.currentThread());
                return "异步线程开启！";
            }
        };
        System.out.println("thread 1 end"+Thread.currentThread());
        return callable;
    }


    @Autowired
    private DeferredResultQueue deferredResultQueue;

    @ResponseBody
    @RequestMapping("/queryOrder")
    public DeferredResult<Object> queryOrder(){
        // 这里我不设置超时时间
        DeferredResult<Object> deferredResult = new DeferredResult<Object>((long)20000,"暂时还没有订单呢!");
        deferredResultQueue.save(deferredResult);
        return deferredResult;
    }


    @ResponseBody
    @RequestMapping("/createOrder")
    public String createOrder(){
        // 新增加了一个订单
        String order = UUID.randomUUID().toString();
        DeferredResult deferredResult = deferredResultQueue.get();
        deferredResult.setResult(order);
        return "success=======>i order some thing~："+order;
    }
}
